<?php
//创建Server对象，监听 127.0.0.1:9501端口
$serv = new swoole_server("127.0.0.1", 9501);

$led_status=0;

//监听连接进入事件
$serv->on('connect', function ($serv, $fd) {  
    echo "Client: Connect.\n";
});

//监听数据接收事件
$serv->on('receive',
    function ($serv, $fd, $from_id, $data)
    {
        global $led_status;
        $client_data=json_decode($data,true);
        $re=['code'=>0,'msg'=>'success','data'=>null];
        echo $client_data['function']."\n";
        switch($client_data['function'])
        {
            case 'get_temperature':
                $re['data']=30;
                break;
            case 'get_led_status':
                $re['data']=$led_status;
                break;
            case 'switch_led':
                if($led_status==0)
                {
                    $led_status=1;
                }
                elseif ($led_status==1)
                {
                    $led_status=0;
                }
                echo $led_status."\n";
                break;
            default:
                $re['code']=99;
                $re['msg']='无对应函数';
        }

        $re=json_encode($re);
        $serv->send($fd, $re);
    }
);

//监听连接关闭事件
$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});



//启动服务器
$serv->start(); 